package com.bobo.encryption.symmetric;

import java.security.Key;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec; 
import com.sun.org.apache.xerces.internal.impl.dv.util.HexBin;

/**
 * Java实现对称加密 （PBE）
 * 加密级别 DES<3DES<AES<PBE
 * @author win7
 *
 */
public class PBEtest {

	public static String bobo="www.bobo.com";
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
         JdkPEB();
	}

	public static void JdkPEB(){
		try {
		//1.初始化盐
			SecureRandom secureRandom = new SecureRandom();
			byte[] salt = secureRandom.generateSeed(8);
			//通过口令初始化key秘钥
			String password = "lblb"; //口令
			PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
			SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBEWITHMD5andDES");
			Key key= secretKeyFactory.generateSecret(pbeKeySpec);
	   //2.加密
		 PBEParameterSpec pbeParameterSpec=new PBEParameterSpec(salt, 100);
		 Cipher cipher=Cipher.getInstance("PBEWITHMD5andDES");
		 cipher.init(Cipher.ENCRYPT_MODE, key, pbeParameterSpec); //通过  盐与key秘钥进行加密
		 byte[] result= cipher.doFinal(bobo.getBytes());
		 System.out.println("jdk pbe 加密："+HexBin.encode(result));
		 
	  //3.解密
		 cipher.init(Cipher.DECRYPT_MODE, key,pbeParameterSpec);
		 result= cipher.doFinal(result);
		 System.out.println("jdk pbe 解密："+new String(result));
	 
		} catch (Exception e) {
			// TODO: handle exception
		}
		   
	}
}
